#! /usr/bin/env python
#coding=utf-8

import os,time
import wmi

'''
需要安装wmi模块，wmi模块又需要先安装pywin模块
列出windows系统的服务，启动模式，状态
'''

def listservices(c):
    for service in c.Win32_Service():
        print service.Caption.encode('gbk'),service.StartMode,service.State
    return c


def startservice(sysservs,servicename):
    '''
    启动服务
    '''
    try:
        for s in sysservs.Win32_Service(Name=servicename):
            s.StartService()
        print 'start service',servicename,'ok'
    except Exception,ex:
        print ex

def stopservice(sysservs,servicename):
    '''
    停止服务
    '''
    try:
        for s in sysservs.Win32_Service(Name=servicename):
            s.StopService()
        print 'stop service',servicename,'ok'
    except Exception,ex:
        print ex


def querystatus(c):
    '''
    监控服务状态
    '''
    wql="select name,state,status from Win32_Service where Name='Power'"
    #while True:
    info='begin query service status:%s' % time.ctime()
    for item in c.query(wql):
        logtofile(''.join((info,str(item))))
        #print item
        #if item.State.upper()=='STOPPED':
        #    return
        #time.sleep(3)


def logtofile(info):
    '''
    记录监控信息到日志文件
    '''
    logfile=r'c:/temp/wmimon.log'
    if os.path.isfile(logfile) and os.path.getsize(logfile)>1000000:
        fh=open(logfile,'w')
    else:
        fh=open(logfile,'a')
    fh.write(info)
    fh.close()

def main():
    c = wmi.WMI()
    #sysservs=listservices(c)
    #startservice(sysservs,"MYSQL51")
    #stopservice(sysservs,"MYSQL51")
    querystatus(c)
    
if __name__=='__main__':
    main()
    